<template>
  <div class="health-container">
    <!-- 导航栏 -->
    <header class="admin-header">
      <!-- 可以添加导航内容 -->
    </header>

    <!-- 主要内容 -->
    <main class="main-content">
      <div class="container">
        <div class="manager-center">
          <h2>管理员中心</h2>

          <div class="profile-section">
            <div class="profile-header">
              <h3>个人信息</h3>
              <el-button type="primary" @click="showEditDialog" class="edit-btn">修改信息</el-button>
            </div>

            <div class="profile-info">
              <div class="info-item">
                <span class="info-label">ID：</span>
                <span class="info-value">{{ managerInfo.id }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">用户名：</span>
                <span class="info-value">{{ managerInfo.username }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">姓名：</span>
                <span class="info-value">{{ managerInfo.realName}}</span>
              </div>
              <div class="info-item">
                <span class="info-label">电话：</span>
                <span class="info-value">{{ managerInfo.phone}}</span>
              </div>
              <div class="info-item">
                <span class="info-label">邮箱：</span>
                <span class="info-value">{{ managerInfo.email}}</span>
              </div>
              <div class="info-item">
                <span class="info-label">创建时间：</span>
                <span class="info-value">{{ formatDate(managerInfo.createTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 修改信息弹窗 -->
    <el-dialog v-model="editDialogVisible" title="修改管理员信息" width="600px" class="edit-dialog">
      <el-form :model="managerForm" label-width="100px" :rules="rules" ref="managerFormRef">
        <el-form-item label="用户名">
          <el-input v-model="managerForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="managerForm.password" type="password" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="managerForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="managerForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="managerForm.email"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="submitUpdate" class="save-btn">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 页脚 -->
    <footer class="app-footer">
      <div class="container">
        <div class="footer-content">
          <p class="footer-title">安心陪诊后台管理系统</p>
          <p class="footer-links">
            &copy; 2025 安心陪诊平台 版权所有 |
            <a href="#" @click.prevent="goToUserAgreement">用户协议</a> |
            <a href="#" @click.prevent="goToPrivacyPolicy">隐私政策</a>
          </p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import {ref, onMounted} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const router = useRouter();

const managerInfo = ref({
  id: "",
  username: "",
  password: "",
  realName: "",
  phone: "",
  email: "",
  createTime: ""
});

const managerForm = ref({
  id: "",
  username: "",
  password: "",
  realName: "",
  phone: "",
  email: ""
});

const managerFormRef = ref(null);
const editDialogVisible = ref(false);
const loading = ref(true);

// 表单验证规则
const rules = {
  realName: [
    {required: false, message: '请输入姓名', trigger: 'blur'},
    {min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur'}
  ],
  phone: [
    {required: false, message: '请输入手机号码', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ],
  email: [
    {required: false, message: '请输入邮箱地址', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
  ]
};

// 获取管理员信息
const fetchManagerInfo = async () => {
  try {
    loading.value = true;

    // 首先尝试从 localStorage 读取管理员信息
    const storedManager = localStorage.getItem('managerInfo');
    if (storedManager) {
      const parsedManager = JSON.parse(storedManager);
      managerInfo.value = parsedManager;
      managerForm.value = {
        id: parsedManager.id,
        username: parsedManager.username,
        password: "********", // 密码不存储明文
        realName: parsedManager.realName,
        phone: parsedManager.phone,
        email: parsedManager.email
      };
    }

    // 无论是否有本地存储，都请求最新数据
    const response = await axios.post(BASE_URL + '/v1/manager/personal', {}, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('managerToken')}`
      }
    });

    if (response.data.state === 2000) {
      const newManagerInfo = {
        id: response.data.data.id || "",
        username: response.data.data.username || "",
        password: response.data.data.password || "",
        realName: response.data.data.realName || "",
        phone: response.data.data.phone || "",
        email: response.data.data.email || "",
        createTime: response.data.data.createTime || ""
      };

      // 更新本地存储
      localStorage.setItem('managerInfo', JSON.stringify(newManagerInfo));

      // 更新界面数据
      managerInfo.value = newManagerInfo;
      managerForm.value = {
        id: newManagerInfo.id,
        username: newManagerInfo.username,
        password: "********",
        realName: newManagerInfo.realName,
        phone: newManagerInfo.phone,
        email: newManagerInfo.email
      };
    } else {
      ElMessage.error(response.data.message || "获取管理员信息失败");
    }
  } catch (error) {
    console.error("获取管理员信息出错:", error);
    if (!localStorage.getItem('managerInfo')) {
      ElMessage.error(error.response?.data?.message || "获取管理员信息失败");
    }
  } finally {
    loading.value = false;
  }
};

// 显示编辑对话框
const showEditDialog = () => {
  // 填充表单数据
  managerForm.value = {
    id: managerInfo.value.id,
    username: managerInfo.value.username,
    password: "********",
    realName: managerInfo.value.realName,
    phone: managerInfo.value.phone,
    email: managerInfo.value.email
  };
  editDialogVisible.value = true;
};

// 提交更新
const submitUpdate = async () => {
  try {
    await managerFormRef.value.validate();

    const updateData = {
      id: managerForm.value.id,
      realName: managerForm.value.realName,
      phone: managerForm.value.phone,
      email: managerForm.value.email
    };

    const response = await axios.post(BASE_URL + '/v1/manager/update', updateData, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('managerToken')}`
      }
    });

    if (response.data.state === 2000) {
      ElMessage.success("信息更新成功");
      await fetchManagerInfo(); // 刷新数据
      editDialogVisible.value = false;
    } else {
      ElMessage.error(response.data.message || "更新失败");
    }
  } catch (error) {
    console.error("更新管理员信息出错:", error);
    if (error.name !== 'ValidationError') {
      ElMessage.error(error.response?.data?.message || "更新失败");
    }
  }
};

const formatDate = (dateString) => {
  if (!dateString) return "未知";
  try {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-');
  } catch (e) {
    return dateString; // 如果日期格式解析失败，返回原始字符串
  }
};

const goToUserAgreement = () => {
  router.push("/userAgreement");
};

const goToPrivacyPolicy = () => {
  router.push("/privacyPolicy");
};

onMounted(() => {
  fetchManagerInfo();
});
</script>

<style scoped>
.health-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8fafc;
}

.admin-header {
  background-color: #a6d2ff;
  color: white;
  padding: 15px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.main-content {
  flex: 1;
  padding: 40px 0;
  background-color: #f8fafc;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.manager-center {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 40px;
  margin-top: 20px;
}

.manager-center h2 {
  font-size: 28px;
  margin-bottom: 30px;
  color: #303133;
  text-align: center;
  font-weight: 600;
  position: relative;
  padding-bottom: 15px;
}

.manager-center h2::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 3px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  border-radius: 3px;
}

.profile-section {
  margin-top: 30px;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.profile-header h3 {
  font-size: 20px;
  color: #303133;
  font-weight: 500;
}

.edit-btn {
  border-radius: 6px;
  padding: 10px 20px;
}

.profile-info {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px dashed #f0f2f5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-weight: 500;
  color: #606266;
  width: 120px;
  font-size: 15px;
}

.info-value {
  flex: 1;
  color: #303133;
  font-size: 15px;
}

/* 弹窗样式 */
.edit-dialog {
  border-radius: 12px;
}

.edit-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

.edit-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.cancel-btn {
  border-radius: 6px;
  padding: 10px 20px;
}

.save-btn {
  border-radius: 6px;
  padding: 10px 20px;
}

/* 页脚样式 */
.app-footer {
  background-color: #f5f7fa;
  padding: 25px 0;
  border-top: 1px solid #e6e6e6;
  margin-top: 40px;
}

.footer-content {
  text-align: center;
}

.footer-title {
  color: #606266;
  margin-bottom: 12px;
  font-size: 15px;
}

.footer-links {
  color: #909399;
  font-size: 13px;
}

.footer-links a {
  color: #909399;
  transition: color 0.3s;
  margin: 0 5px;
}

.footer-links a:hover {
  color: #a6d2ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }

  .manager-center {
    padding: 25px 20px;
  }

  .manager-center h2 {
    font-size: 24px;
  }

  .profile-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }

  .info-label {
    width: 100%;
  }

  .edit-dialog {
    width: 90% !important;
  }
}

/* 基础样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB',
  'Microsoft YaHei', Arial, sans-serif;
}

body {
  background-color: #f8fafc;
  color: #333;
  line-height: 1.6;
}

a {
  text-decoration: none;
  color: inherit;
}

ul {
  list-style: none;
}
</style>